package com.gz.controller;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gz.common.ApplicationrecordService;
import com.gz.common.UserService;
import com.gz.common.model.Applicationrecord;

import com.gz.common.model.User;
import com.gz.utils.Response;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

/**
 * 分销Controller
 * 
 * @author 尹公子
 *
 */
public class ApplicationrecordController extends Controller {

	/**
	 * @author 尹公子 
	 * 	申请分销、添加申请分销记录
	 * @param Applicationrecord.Class
	 * @param
	 * @return 成功1004 失败1005
	 */
	public void addingApplicationRecords() {
		Applicationrecord app = new Applicationrecord();
		// 获取手机号码
		String mobile = getPara("mobile");
		// 判断上级手机号参数
		if (mobile == null) {
			renderJson(Response.responseJson(1005, "mobile参数错误"));
			return;
		}
		// 获取上级id
		User user = ApplicationrecordService.getService().findSuperiorId(mobile);
		// 判断上级用户是否存在
		if (user == null) {
			renderJson(Response.responseJson(1005, "上级不存在"));
			return;
		}
		// 受理用户
		app.setAcceptor(user.getId());
		// 申请用户
		app.setRecorduser(getParaToInt("userId"));
		// 申请级别
		app.setRecordrank(getParaToInt("recordrank"));
		// 申请状态 0未受理
		app.setAgree(0);
		boolean result = ApplicationrecordService.getService().addingApplicationRecords(app);
		if (!result) {
			renderJson(Response.responseJson(1005, "申请失败"));
			return;
		}
		renderJson(Response.responseJson(1004, "申请成功"));
	}

	/**
	 * @author 尹公子 查询上级是否存在
	 * @param mobile 手机号码
	 */
	public void findSuperiorId() {
		// 获取手机号码
		String mobile = getPara("mobile");
		User user = ApplicationrecordService.getService().findSuperiorId(mobile);
		// 判断上级是否存在
		if (user != null) {
			renderJson(Response.responseJson(1001, "上级存在"));
		} else {
			renderJson(Response.responseJson(1002, "上级不存在"));
		}
	}

	/**
	 * 根据用户id分页查询审核记录
	 * 
	 * @param userId     用户id
	 * @param pageNumber 当前页
	 * @param pageSize   显示记录数
	 * @param agree，1代表未审核，2代表同意和不同意，0代表全部
	 * @return code:1006-成功：1007-失败，msg:查询成功，data：page
	 * @author px
	 * @http:http://localhost:8080/cms-api/appli/getApplicationrecordList?userId=12& pageNumber=1&agree=0
	 */
	public void getApplicationrecordList() {
		String userId = getPara("userId");
		Integer pageNumber = getParaToInt("pageNumber");
		Integer pageSize = getParaToInt("pageSize");
		Integer agree = getParaToInt("agree");
		// 如果没有获取到agree则默认查询全部
		if (agree == null) {
			agree = 0;
		}
		try {
			Page<Applicationrecord> page = ApplicationrecordService.getService().getApplicationrecordList(userId, agree,
					pageNumber, pageSize);
			// 查询结果存在记录返回page集合否则返回null
			if (page.getList().size() > 0) {
				renderJson(Response.responseJson(1006, "查询成功！", page));
			} else {
				renderJson(Response.responseJson(1007, "查询失败！", null));
			}
		} catch (Exception e) {
			e.printStackTrace();
			// 如果查询异常则返回1008-查询异常-null
			renderJson(Response.responseJson(1008, "查询异常！", null));
		}
	}
	
	

	/**
	 * @author ZhangZhangyi Description:传入用户id查询需要当前用户审核记录
	 * @author v ZhangZhangyi
	 * Description:传入用户id查询需要当前用户审核记录
	 * @param acceptor 需要当前用户审核id
	 * @return list 审核记录集合
	 *         http://localhost:8080/cms-api/appli/findApplicationrecordsByUserId
	 */
	public void findApplicationrecordsByUserId() {
		int acceptor = getParaToInt("acceptor");
		List<Applicationrecord> list = ApplicationrecordService.getService().getApplicationrecordsByUserId(acceptor);
		// list不为空返回查询结果
		if (list != null) {
			renderJson(Response.responseJson(1006, "查询成功", list));
		} else {
			renderJson(Response.responseJson(1007, "查询失败", null));
		}
	}

	/**
	 * @author ZhangZhanyi Description:传入审核记录id查到审核记录后再传入状态id修改状态
	 * @param recordid 审核id
	 * @param agree    同意 1 不同意 2
	 * @return 成功 1010 失败 1011
	 *         http://localhost:8080/cms-api/appli/findApplicationrecordsByUserId
	 */
	public void MvApplicationrecordAgree() {
		int recordid = getParaToInt("recordid");
		int agree = getParaToInt("agree");
		// 根据审核记录id查询得到审核记录
		Applicationrecord applicationrecord = ApplicationrecordService.getService().findApplicationrecord(recordid);
		// 如果审核对象不为null则修改审核状态
		if (applicationrecord != null) {
			applicationrecord.setAgree(agree);
			boolean judge = ApplicationrecordService.getService().Mvapplicationrecord(applicationrecord);
			// 修改成功返回1010 失败返回1011
			if (judge) {
				renderJson(Response.responseJson(1010, "修改成功"));
				//通过申请表编号查询出申请的用户信息
				User user = ApplicationrecordService.getService().findUserRecordid(recordid);
				//通过申请表编号查询出申请表信息
				Applicationrecord appl = ApplicationrecordService.getService().findAppli(recordid);
				//升级成功 等级+1
				user.setUsergrade(user.getUsergrade()+1);
				//给上级编号赋值
				if(user.getSuperiorid()==0) {
					user.setSuperiorid(appl.getRecordid());
				}
				ApplicationrecordService.getService().xiugaiuser(user);
			} else {
				renderJson(Response.responseJson(1011, "修改失败"));
			}
		} else {
			renderJson(Response.responseJson(0, "没查询到对象"));
		}
	}

	/**
	 * @author 尹公子 申请分销
	 */
	public void getshenqing(String moblie,Integer userId) {
		String SuperiorMobile = null;
		User user = null;
		if (moblie != null) {
			// 获取手机号码
			SuperiorMobile = moblie;
			Applicationrecord app = new Applicationrecord();
			// 获取上级id
			User usersj = ApplicationrecordService.getService().findSuperiorId(SuperiorMobile);
			// 判断上级用户是否存在
			if (usersj == null) {
				renderJson(Response.responseJson(1005, "上级不存在"));
				return;
			}
			// 受理用户
			app.setAcceptor(usersj.getId());
			// 申请用户
			app.setRecorduser(userId);
			// 申请级别
			app.setRecordrank(1);
			// 申请状态 0未受理
			app.setAgree(1);
			boolean result = ApplicationrecordService.getService().addingApplicationRecords(app);
			user = UserService.getService().findUserId(userId);
			if (!result) {
				renderJson(Response.responseJson(1005, "发送申请失败"));
				return;
			}
			
		} else {
			
			// 查询申请用户等级
			//User user = ApplicationrecordService.getService().findDJ(getParaToInt("userId"));
			user = ApplicationrecordService.getService().findDJ(userId);
			// 返回上级用户id
			//Integer userid = getAcceptor(user.getUsergrade(), getParaToInt("userId"));
			Applicationrecord app = new Applicationrecord();
			// 受理用户
			app.setAcceptor(user.getSuperiorid());
			// 申请用户
			app.setRecorduser(user.getId());
			// 申请级别
			app.setRecordrank((user.getUsergrade()+1));
			// 申请状态 0未受理
			app.setAgree(1);
			boolean result = ApplicationrecordService.getService().addingApplicationRecords(app);
			if (!result) {
				renderJson(Response.responseJson(1005, "发送申请失败"));
				return;
			}
		}
		shengJi(SuperiorMobile, user);
		renderJson(Response.responseJson(1004, "发送申请成功"));
	}

	/**
	 * @author 尹公子 递归
	 * @param userLevel 用户等级
	 * @param userid    用户id
	 * @return
	 */
	public Integer getAcceptor(Integer userLevel, Integer userid) {
		// 查询用户信息
		User userAcceptor = ApplicationrecordService.getService().findDJ(userid);
		// 判断上级用户等级是否大于申请用户目前的等级 大于则可以直接申请返回上级id 否则将当前用户id查询出来的的上级用户传入递归
		if (userAcceptor.getUsergrade() > userLevel) {
			return userAcceptor.getId();
		} else {
			return getAcceptor(userLevel, userAcceptor.getSuperiorid());
		}
	}
	
	/**
	 * @Url http://localhost:8080/cms-api/appli/findIsAgree?userId=17
	 * @author 绝爷
	 * @param userId
	 * @return -1表示可以申请,0正在审核,1已经是分销商
	 */
	public void findIsAgree() {
		Applicationrecord applicationrecord = ApplicationrecordService.getService().findIsAgree(getParaToInt("userId"));
		User user = UserService.getService().findUserId(getParaToInt("userId"));
		if(applicationrecord!=null) {
			applicationrecord.setUser(user);
			renderJson(Response.responseJson(1001, "SUCCESS",applicationrecord));
		}else {
			renderJson(Response.responseJson(-1, "可以申请"));
		}
	}
	
	/**
	 * @author 尹公子 
	 * 用户升级修改用户信息
	 */
	public void shengJi(String mobile,User user) {
		//升级成功 等级+1
		user.setUsergrade(user.getUsergrade()+1);
		//给上级编号赋值
		if(mobile!=null) {
			//通过手机号码查询上级id
			int id = ApplicationrecordService.getService().findSuperiorId(mobile).getId();
			user.setSuperiorid(id);
		}
		if(UserService.getService().modifyUserGrade(user)) {
			renderJson(Response.responseJson(1001, "SUCCESS"));
			return;
		}
		renderJson(Response.responseJson(1001, "FAIL"));
	}
	
	/**
	 * 	判断用户以及他的上级是否可以升级
	 * @param mobile
	 * @param userId
	 * 0-普通用户，1-会员，2-分销商，3-总分销
	 * @Url http://localhost:8080/cms-api/appli/isUpgrade?mobile
	 */
	public void isUpgrade() {
		
		Integer userId=getParaToInt("userId");	//当前用户
		
		if (getPara("mobile") == null) {
			/*获取当前用户*/
			User user =UserService.getService().findUserId(userId);
			
			//判断该用户是否是会员
			if(user.getSuperiorid()!=null&&user.getSuperiorid()!=0) {
			
				/*获取上级用户*/
				User shangjiUser = UserService.getService().findUserId(user.getSuperiorid());
				
				//判断当前用户是否可以直接升级
				Integer userGrade = user.getUsergrade();	//获取当前用户等级
				Integer userAppliCount = UserService.getService().findAppliByUser(user.getId());	//当前用户下的分销商数量
				if((userGrade<2&&userGrade>0)||userGrade==2&&userAppliCount>=10) {
					getshenqing(null,user.getId());
				}
				/*判断上级下是否有10个分销商并且上级不是总分销*/
				Integer shangjiUserGrade = shangjiUser.getUsergrade();	//获取上级用户等级
				userAppliCount = UserService.getService().findAppliByUser(shangjiUser.getId());		//上级用户下的分销商数量
				if(userAppliCount>=10&&shangjiUserGrade<3) {
					getshenqing(null,shangjiUser.getId());
				}
			}
		}else {
			getshenqing(getPara("mobile"),userId);
		}
	}
	
}
